package com.bt.lms.ui.action.teaching.plan.query;

import com.alibaba.fastjson.JSON;
import com.bt.lms.constants.TeachingPlanBizTypeConstant;
import com.bt.lms.entity.page.Page;
import com.bt.lms.network.msg.ReqMsg;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.control.TableView;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 首页事件
 * 条件分页查询
 *
 * @author 李舒淇
 */
public class FirstLabAction implements EventHandler {



    /**
     * 表格
     */
    public TableView tableView;

    public int current;



    public FirstLabAction(TableView tableView, int current) {

        this.tableView = tableView;
        this.current = current;
    }

    @Override
    public void handle(Event event) {

        //1、组包

        byte[] msgByte = handle2ReqMsgPacket();

        //2、组网
        Socket socket = getNet();

        //3、发送消息
        OutputStream out = sendReqMsgPacket(socket, msgByte);

        //4、接收消息
        byte[] acceptBuffer = acceptReqMsgPacket(socket, out);

        //5、解包
        UnbindPackage unbindP = new UnbindPackage();
        unbindP.unbindPackage(acceptBuffer,tableView);


    }



    /**
     * 4、接收消息
     *
     * @param socket
     * @param out
     * @return
     */
    private byte[] acceptReqMsgPacket(Socket socket, OutputStream out) {

        byte[] acceptBuffer = new byte[2100];

        try {
            InputStream in = socket.getInputStream();
            in.read(acceptBuffer);
            in.close();
            out.close();
            socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return acceptBuffer;
    }

    /**
     * 3、发送消息
     *
     * @param socket  网
     * @param msgByte 数组
     * @return 是否成功
     */
    private OutputStream sendReqMsgPacket(Socket socket, byte[] msgByte) {

        OutputStream out = null;
        try {
            out = socket.getOutputStream();
            out.write(msgByte);
            out.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        return out;
    }


    /**
     * 2、组网
     *
     * @return
     */
    private Socket getNet() {

        String serverip = "127.0.0.1";
        int port = 8888;
        Socket socket = null;
        try {
            socket = new Socket(serverip, port);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return socket;
    }


    /**
     * 1、组包
     * @return
     */
    private byte[] handle2ReqMsgPacket() {

        Page page = new Page();
        page.setCurrent(current);

        String jsonStr = JSON.toJSONString(page);


        ReqMsg reqMsg = new ReqMsg();
        reqMsg.setBizType(TeachingPlanBizTypeConstant.PLAN_QUERY);
        reqMsg.setData(jsonStr);

        byte[] msgByte = reqMsg.toBytes();

        return msgByte;
    }
}
